<?php

/**
 * ringtone_remove actions.
 *
 * @package    sf_sandbox
 * @subpackage ringtone_remove
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class ringtone_removeActions extends sfActions //autoringtone_removeActions
{
  public function executeIndex()
  {
    return $this->forward('ringtone_remove', 'list');
  }

  public function executeList()
  {
    $limit = 20;
    $this->page = $this->getRequestParameter('page',1);
    $filters = null;
    if ($this->getRequest()->hasParameter('filter')){
    	$val = $this->getRequestParameter('filters');
		$filters['id'] = $val['id'];    
		$filters['name'] = $val['name'];    
		$filters['rbtcode'] = $val['rbt_code'];    
    }
    $this->filters = $filters;
    #echo "<pre>";print_r($this->filters);exit();
    $total = RingtonePeer::getTotalRemove($this->filters);
	$this->totalPage = floor($total/$limit);
	if (($total/ $limit) - $this->totalPage > 0){
		$this->totalPage += 1;
	}
    if($this->page > $this->totalPage && $this->totalPage>0){
        $this->page = $this->totalPage;
    }
    $offset = ($this->page-1)*$limit;
    $this->pager= RingtonePeer::getlistRemove($limit, $offset,$this->filters);
    
    $this->res = $this->getRequestParameter('res');
    $this->total = $total;
  }

  private function hideOrResumeRbt($mode, $toneID) {
        //mode 1: hide
        //mode 2: resume
        $ret = false;
        try {
            $queryToneEvt = new HiddenAndResumeToneEvt(
                sfConfig::get('portalAccount'),
                sfConfig::get('portalPwd'),
                sfConfig::get('portalType'),
                null,"3","admin",$mode,
                "1",trim($toneID)
            );

            $crbtCaller = new CRBTCaller();
            $querySettingResp = $crbtCaller->exec($queryToneEvt,
                'HiddenAndResumeToneEvt', 'hiddenAndResumeTone',
                sfConfig::get('ToneProvide_wsdl'),
                sfConfig::get('ToneProvide_namespace'));

            $retCode = $querySettingResp->returnCode;

            //echo $retCode."<br/>";

            if ($retCode == '000000'){
                $ret = true;
                //synclog("hideOrResumeRbt: OK: toneID = $toneID, mode = $mode");
            }else{
                $ret = false;
                //synclog("hideOrResumeRbt: FAILED: $retCode: toneID = $toneID, mode = $mode");
            }
        } catch (Exception $e) {
            //synclog("hideOrResumeRbt: Exception = ".$e->getMessage().", toneID = $toneID, mode = $mode");
        }

        return $ret;
    }

  private function deleteRbt($toneID){
        $ret = false;

        try {
            $queryToneEvt = new DelToneEvt(
                sfConfig::get('portalAccount'),
                sfConfig::get('portalPwd'),
                sfConfig::get('portalType'),
                null,"3","admin",trim($toneID)
            );

            $crbtCaller = new CRBTCaller();
            $querySettingResp = $crbtCaller->exec($queryToneEvt,
                'DelToneEvt', 'delTone',
                sfConfig::get('ToneProvide_wsdl'),
                sfConfig::get('ToneProvide_namespace'));

            $retCode = $querySettingResp->returnCode;

            if ($retCode == '000000'){
                $ret = true;
                //synclog("deleteRbt: OK: toneID = $toneID");
            }else{
                //synclog("deleteRbt: FAILED: $retCode: toneID = $toneID");
            }
        } catch (Exception $e) {
            //synclog("deleteRbt: Exception = ".$e->getMessage().", toneID = $toneID");
        }

        return $ret;
    }
  
  private  function date_diff($date1, $date2) {
        $time1 = strtotime($date1);
        $time2 = strtotime($date2);
        $diff = floor(($time2 - $time1)/86400);
        return $diff;
    }

  public function executeRestore()
  {
        $rtId = $this->getRequestParameter('id',null);
        $rtCode = $this->getRequestParameter('code',null);

        $msg = "";

        $approvedType = '2';
        $queryToneEvt = new QueryToneEvt(
                            sfConfig::get('portalAccount'),
                            sfConfig::get('portalPwd'),
                            sfConfig::get('portalType'),
                            null,null,null,null,
                            trim($rtCode),$approvedType
                        );

        $crbtCaller = new CRBTCaller();
        $querySettingResp = $crbtCaller->exec($queryToneEvt, 'QueryToneEvt', 'queryTone', sfConfig::get('ToneProvide_wsdl'), sfConfig::get('ToneProvide_namespace'));
        if (($querySettingResp->returnCode == '000000')&&(count($querySettingResp->queryToneInfos) == 1)){
            $toneInfoArr = $querySettingResp->queryToneInfos;
            $toneInfo = $toneInfoArr[0];

            $msg = "Query $rtCode to CRBT OK: ".$toneInfo->toneID;
            

            sfContext::getInstance()->getLogger()->err('Resume ringtone');
            $rtHide = $this->hideOrResumeRbt("2", $toneInfo->toneID);
            if($rtHide){
                sfContext::getInstance()->getLogger()->err('Resume ringtone SUCCESS  rtid: '.$rtId);
                // Resume on IMS
                RingtonePeer::resum_rt_hidentime($rtId);
                RingtonePeer::resum_rt_status($rtId);
                $msg = "Restore lại trạng thái nhạc chờ $rtCode, toneID=".$toneInfo->toneID.", rtHide=$rtHide";
            } else {
                sfContext::getInstance()->getLogger()->err('Resume ringtone FAIL  rtCode: '.$rtCode);
                $msg = 'Không restore lại được trạng thái nhạc chờ '.$rtCode.", hide=$rtHide, toneID=".$toneInfo->toneID;
            }

        } else {
            $msg = "Query $rtCode to CRBT failed!!";
        }

        //echo $msg;
        //exit();

        return $this->redirect('ringtone_remove/list/?res='.$msg);
  }
      
  public function executeDelete()
  {
    $rtId = $this->getRequestParameter('id',null);
    $rtCode = $this->getRequestParameter('code',null);

    $approvedType = '2';
    $queryToneEvt = new QueryToneEvt(
                        sfConfig::get('portalAccount'),
                        sfConfig::get('portalPwd'),
                        sfConfig::get('portalType'),
                        null,null,null,null,
                        trim($rtCode),$approvedType
                    );

    $crbtCaller = new CRBTCaller();
    $querySettingResp = $crbtCaller->exec($queryToneEvt, 'QueryToneEvt', 'queryTone', sfConfig::get('ToneProvide_wsdl'), sfConfig::get('ToneProvide_namespace'));
 	
    /*echo $querySettingResp->returnCode;
    echo '<br/>';
    echo "<pre>";print_r($querySettingResp);exit();*/
    $msg = "";
    if (($querySettingResp->returnCode == '000000')&&(count($querySettingResp->queryToneInfos) == 1)){
    	$toneInfoArr = $querySettingResp->queryToneInfos;
        $toneInfo = $toneInfoArr[0];
        
        // Lay ra thong tin cua ringtone tu he thong IMS
        $ringtone_ims = RingtonePeer::getringtone_ims($rtId);
        $hide_time = $ringtone_ims[0]['imuzik_hidden_time']; // Total set on IMS
        $totalset = $ringtone_ims[0]['total_set'];// Time hide on IMS
        
        $currentDatetime = date('Y-m-d H:i:s');
        $day = $this->date_diff($hide_time,$currentDatetime);
        if(($toneInfo->status == 2) && ($hide_time != null) && ($day >= 3) && ($toneInfo->orderTimes <= $totalset) ){
            $rtDel = $this->deleteRbt($toneInfo->toneID);
            if($rtDel){
                sfContext::getInstance()->getLogger()->err('Delete ringtone SUCCESS rtid: '.$rtId);
                RingtonePeer::reject_rbt_rt($rtId);
                RingtonePeer::reject_rbt_rt_status($rtId);
                RingtonePeer::delete_rbt_rt_status($rtId);
                $msg = 'Đã xóa thành công nhạc chờ '.$rtId;
            } else {
                sfContext::getInstance()->getLogger()->err('Delete ringtone FAIL rtid: '.$rtId);
                $msg = 'Không xóa được nhạc chờ '.$rtId;
            }
        } else if($toneInfo->orderTimes > $totalset){
            $msg = "Nhạc chờ $rtCode có phát sinh lượt tải. Dùng chức năng Restore để khôi phục! Tránh restore nhầm bài vi phạm!";

            /*
            sfContext::getInstance()->getLogger()->err('Resume ringtone');
            $rtHide = $this->hideOrResumeRbt("2", $toneInfo->toneID);
            if($rtHide){
                sfContext::getInstance()->getLogger()->err('Resume ringtone SUCCESS  rtid: '.$rtId);
                // Resume on IMS
                RingtonePeer::resum_rt_hidentime($rtId);
                RingtonePeer::resum_rt_status($rtId);
                $msg = 'Restore lại trạng thái nhạc chờ '.$rtId;
            } else {
                sfContext::getInstance()->getLogger()->err('Resume ringtone FAIL  rtid: '.$rtId);
                $msg = 'Không restore lại được trạng thái nhạc chờ '.$rtId;
            }
             * 
             */
        } else {
            $msg = "Không xoá được nhạc chờ nào: status=$toneInfo->status, hiddentime=$hide_time, day=$day, orderTimes=$toneInfo->orderTimes, totalSet=$totalset!!";
        }
    }else{
    	$msg = 'Nhạc chờ '.$rtId.' không query tới CRBT được';
    }
    $page = $this->getRequestParameter('page',1);
    return $this->redirect('ringtone_remove/list/?page='.$page.'&res='.$msg);
  }

}
